package com.gzdh.tang.ali.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzdh.tang.comm.handler.IPayRuleHandler;
import com.gzdh.tang.comm.vo.Result;
import com.gzdh.tang.config.weixin.WXEntity;
import com.gzdh.tang.config.weixin.WXPay;
import com.gzdh.tang.config.weixin.WXPayUtil;
import com.gzdh.tang.config.weixin.WXPayUtils;
import com.gzdh.tang.modu.entity.*;
import com.gzdh.tang.modu.model.DeviceCarModel;
import com.gzdh.tang.modu.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("api/v2/pay")
public class AliPayController {


    @Autowired
    MacMainpSbruanService macMainpSbruanService;

    @Autowired
    MacMainpSbruanPayruleService macMainpSbruanPayruleService;

    @Autowired
    MacMainpSbruanOrdersService macMainpSbruanOrdersService;

    @Autowired
    FkService fkService;

    @Autowired
    GsService gsService;

    /**
     * 支付宝刷卡操作,通用入口
     *
     * @param jsonObject
     * @return
     */
    @PostMapping("cardPay")
    public Result<Object> cardPay(@RequestBody JSONObject reqJson) {
        Result<Object> result = new Result<>();
        String deviceId = reqJson.getString("deviceId");
        if (StringUtils.isEmpty(deviceId)) {
            return Result.error("参数错误，请核对参数是否正确");
        }
        MacMainpSbruan macMainpSbruan = macMainpSbruanService.getOne(new QueryWrapper<MacMainpSbruan>().lambda().eq(MacMainpSbruan::getMac, deviceId));
        if (macMainpSbruan == null) {
            return Result.error("设备未找到或者设备有误，请核对操作");
        }
        try {
            MacMainpSbruanPayrule macMainpSbruanPayrule = macMainpSbruanPayruleService.getById(macMainpSbruan.getPayRule());
            IPayRuleHandler ruleHandler = (IPayRuleHandler) Class.forName(macMainpSbruanPayrule.getClassName()).newInstance();
            JSONObject resJson = ruleHandler.toCardPay(reqJson);
            result.setResult(resJson);
        } catch (Exception e) {
            return Result.error("系统错误：" + e.getMessage());
        }
        return result;
    }


    @PostMapping("facePay")
    public Result<Object> facePay(@RequestBody JSONObject reqJson) {
        Result<Object> result = new Result<>();
        String deviceId = reqJson.getString("deviceId");
        if (StringUtils.isEmpty(deviceId)) {
            return Result.error("参数错误，请核对参数是否正确");
        }
        MacMainpSbruan macMainpSbruan = macMainpSbruanService.getOne(new QueryWrapper<MacMainpSbruan>().lambda().eq(MacMainpSbruan::getMac, deviceId));
        if (macMainpSbruan == null) {
            return Result.error("设备未找到或者设备有误，请核对操作");
        }
        try {
            MacMainpSbruanPayrule macMainpSbruanPayrule = macMainpSbruanPayruleService.getById(macMainpSbruan.getPayRule());
            IPayRuleHandler ruleHandler = (IPayRuleHandler) Class.forName(macMainpSbruanPayrule.getClassName()).newInstance();
            JSONObject resJson = ruleHandler.toFacePay(reqJson);
            result.setResult(resJson);
        } catch (Exception e) {
            return Result.error("系统错误：" + e.getMessage());
        }
        return result;
    }


    @PostMapping("qrPay")
    public Result<Object> qrPay(@RequestBody JSONObject reqJson) {
        Result<Object> result = new Result<>();
        String deviceId = reqJson.getString("deviceId");
        if (StringUtils.isEmpty(deviceId)) {
            return Result.error("参数错误，请核对参数是否正确");
        }
        MacMainpSbruan macMainpSbruan = macMainpSbruanService.getOne(new QueryWrapper<MacMainpSbruan>().lambda().eq(MacMainpSbruan::getMac, deviceId));
        if (macMainpSbruan == null) {
            return Result.error("设备未找到或者设备有误，请核对操作");
        }
        try {
            MacMainpSbruanPayrule macMainpSbruanPayrule = macMainpSbruanPayruleService.getById(macMainpSbruan.getPayRule());
            IPayRuleHandler ruleHandler = (IPayRuleHandler) Class.forName(macMainpSbruanPayrule.getClassName()).newInstance();
            JSONObject resJson = ruleHandler.toQrPay(reqJson);
            result.setResult(resJson);
        } catch (Exception e) {
            return Result.error("系统错误：" + e.getMessage());
        }
        return result;
    }

    @GetMapping("readCard")
    public Result<Object> readCard(@RequestParam("cardSn") String cardSn) throws Exception {
        Result<Object> result = new Result<>();
        Fk fk = fkService.getOne(new QueryWrapper<Fk>().lambda().eq(Fk::getCardsn, cardSn));
        if (fk == null) {
            return Result.error("非法卡");
        }
        int gs = gsService.count(new QueryWrapper<Gs>().lambda().eq(Gs::getCardno, fk.getCardno()).eq(Gs::getKh, fk.getKh()));
        if (gs > 0) {
            return Result.error("该卡已挂失");
        }
        result.setResult(fk);
        return result;
    }


    @PostMapping("hexiao")
    public Result<Object> hexiao(@RequestBody JSONObject reqJson) {
        Result<Object> result = new Result<>();
        String deviceId = reqJson.getString("deviceId");
        if (StringUtils.isEmpty(deviceId)) {
            return Result.error("参数错误，请核对参数是否正确");
        }
        MacMainpSbruan macMainpSbruan = macMainpSbruanService.getOne(new QueryWrapper<MacMainpSbruan>().lambda().eq(MacMainpSbruan::getMac, deviceId));
        if (macMainpSbruan == null) {
            return Result.error("设备未找到或者设备有误，请核对操作");
        }
        try {
            MacMainpSbruanPayrule macMainpSbruanPayrule = macMainpSbruanPayruleService.getById(macMainpSbruan.getPayRule());
            IPayRuleHandler ruleHandler = (IPayRuleHandler) Class.forName(macMainpSbruanPayrule.getClassName()).newInstance();
            int payway = reqJson.getInteger("payway");
            JSONObject resJson = new JSONObject();
            if (payway == 0) {
                resJson = ruleHandler.toFacePay(reqJson);
            } else if (payway == 1) {
                resJson = ruleHandler.toQrPay(reqJson);
            } else if (payway == 3) {
                resJson = ruleHandler.toCardPay(reqJson);

            }
            result.setResult(resJson);
        } catch (Exception e) {
            return Result.error("系统错误：" + e.getMessage());
        }
        return result;
    }


    @GetMapping("checkOrder")
    public Result<Object> checkOrder(@RequestParam("deviceOrders") String deviceOrders) {
        Result<Object> result = new Result<>();
        JSONObject jsonObject = new JSONObject();
        MacMainpSbruanOrders macMainpSbruanOrders = macMainpSbruanOrdersService.getOne(new QueryWrapper<MacMainpSbruanOrders>()
                .lambda().eq(MacMainpSbruanOrders::getDeviceOrder, deviceOrders));
        if (macMainpSbruanOrders.getType() == 1) {
            //微信订单；通过微信查询
            try {
                WXEntity wxEntity = new WXEntity();
                WXPay wxPay = new WXPay(wxEntity);
                //start pay
                Map<String, String> reqMap = new HashMap<>();
                reqMap.put("out_trade_no", macMainpSbruanOrders.getOrders());
                if (WXPayUtils.getSubmchMode() == 1) {
                    reqMap.put("sub_mch_id", WXPayUtils.getSubMchId());
                }
                Map<String, String> resMap = wxPay.orderQuery(reqMap);
                System.out.println(resMap.toString());
                log.info(resMap.toString());
                if (!"SUCCESS".equals(resMap.get("return_code")) && !"SUCCESS".equals(resMap.get("result_code"))) {
                    log.info("支付系统错误，需要进行查单");
                    jsonObject.put("state", "ERROR");
                } else if ("SUCCESS".equals(resMap.get("trade_state")) || "ACCEPT".equals(resMap.get("trade_state"))) {
                    //支付成功订单
                    macMainpSbruanOrdersService.paySuccessByDeviceOrders(macMainpSbruanOrders.getDeviceOrder());
                    Fk fk = fkService.getOne(new QueryWrapper<Fk>().lambda().eq(Fk::getCardno, macMainpSbruanOrders.getCardno()));
                    jsonObject.put("state", "SUCCESS");
                    jsonObject.put("fk", fk);
                } else if ("USERPAYING".equals(resMap.get("trade_state"))) {
                    jsonObject.put("state", "USERPAYING");
                } else {
                    jsonObject.put("state", "ERROR");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            result.setResult(jsonObject);
        }
        return result;
    }

}
